# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

import pymysql
# 获取settings中的数据库参数
from scrapy.utils.project import get_project_settings
import pandas as pd

# 存入mysql数据库的管道
class ScrapyReadbook36NewPipeline:

    # 初始化获取settings中的数据库参数
    def __init__(self):
        settings = get_project_settings()
        self.host = settings['DB_HOST']
        self.port = settings['DB_PORT']
        self.user = settings['DB_USER']
        self.password = settings['DB_PASSWORD']
        self.database = settings['DB_DATABASE']
        self.charset = settings['DB_CHARSET']

        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.database,
            charset=self.charset
        )
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):

        sql = 'insert into readbook(name,src,author) values("{}","{}","{}")'.format(item['name'],item['src'],item['author'])
        self.cursor.execute(sql)
        self.conn.commit()

        return item

    def close_spider(self,spider):

        self.cursor.close()
        self.conn.close()

# 下载到excel的管道
class readbookDownloadExcelPipeline:

    def __init__(self):
        # 创建数据框，列名改为汉字的话与item中的数据对不上，excel就会格式不对，所以用item中的数据名
        self.df = pd.DataFrame(columns=['name','src','author'])

    def process_item(self, item, spider):
        # item字典对象转成series对象，才可以操作
        series = pd.Series(item)
        # 数据放入数据框中
        self.df = self.df.append(series,ignore_index=True)

        return item

    def close_spider(self,spider):
        self.df.to_excel('book.xlsx',index=False)